<?php
// 本类由系统自动生成，仅供测试用途
namespace MyClass;
class Sweepstakes extends \C\Action {
	protected static $U;
	protected function _bgin(){
		$user = session("UserInfo");
		$this->s('_user',$user);
		$this->GetLink();
		$this->GetSee();
		$this->GetCompany();
	}
	public function GetLink(){
		$list = $this->m('link')->order('Sort DESC')->select();
		$this->s('link',$list);
	}
	public function GetSee(){
		if($_SESSION['UserInfo']['cid']){
			$UnSee = $this->m("mail")->where("Sid=".$_SESSION['UserInfo']['cid']." AND See=0 And Gdel=0")->count();

		}else{
			$UnSee=0;
		}
		$this->s("_UnSee",$UnSee);

	}
	public function Login(){//活动登陆

		if(!$this->is_login() && \Chinax3::$conf["_action"] != 'LoginDo'){
			$this->v();
			exit;
		}else{
			header("Location:http://wap.chnhuacai.com");
			// $this->success("您已登录", T('Index/Index'));
			
		}
	}
	public function LoginAjaxDo(){
        /*
		if(!$this->isMobile($_REQUEST['username'])){
		   echo 1;
		   exit;
        }
		*/
        if(!$this->isPWD($_POST['password'])) {
		   echo 2;
		   exit;
        }
		$w = array("Phone"=>$_POST['username'],'Password' => $_POST['password']);
		$info = $this->m('user')->where($w)->find();
		if($info){
			if($info['Status'] == -1){
				echo 3;//删除的用户
				exit;
			}else{

				$ifstk = $this->m("sweepstakes")->where("Uid =".$info['Id'])->find();//判断是否存在抽奖卷
				if(!$ifstk){//如果不存在抽奖卷
						$code = md5(rand(0,9999).time());
						$SweepstakesNumber = $this->ScSweepstakesNumber(); //获取6位不重复的数字
						$SweepstakesNumber = $this->SknHq($SweepstakesNumber);//判断数据库中是否存在;
						$dataarr = array(
							'code' => $code,	
							'Uid'  => $info['Id'],	
							'CreateTime' => time(),	
							'Djstatus' => 1,	
							'SweepstakesNumber' => $SweepstakesNumber,
							'MaturityTime' => strtotime(date('Y-m-d'))+24*3600,
							'Ifdel' => 1,
							'Dhstatus' => 1
						
						);
						$res = $this->m("sweepstakes")->add($dataarr);//添加抽奖卷
					if($res){
						$ms = array(
							'content' 	=> '【华采网】恭喜您注册“华采网”成功！并获得品牌充电宝一个!更多机会——特等：价值10000元纪念币一套（1名）；一等：价值5000元华为手机一部(5名)；二等：价值3000元 IPAD MIN4一部(20名)，三等：价值1000元华为手环一个(50名)。具体详情http://www.chnhuacai.com/?m=News&a=NewsContent&id=29',//短信内容

							'mobile' 	=> $_POST['username'],//手机号码
						);
						send($ms);
					}
						if(!$res){
							echo 6;
							exit;
						}
						//echo $SweepstakesNumber;exit;
						//echo  json_encode($code);exit;

				}
				
				if(isset($info['Cid'])){
					$company = $this->m('company')->where("Id = " . $info['Cid'])->find();
				}else{
					$company['CompanyName']="";
				}
				$user = array(
					'id' => $info['Id'],
					'cid' => $info['Cid'],
					'pid' => $info['Pid'],
					'phone' => $info['Phone'],
					'CompanyName' => $company['CompanyName'],
                    'UserPhoto' => $info['UserPhoto'],
				);
				session('UserInfo',$user);
				$this->U = session('UserInfo');
				echo 4;
				exit;
				
			}
		}else{
			echo 5;
			exit;
		}
	}

	public function Register(){//活动注册
		/*if(isset($_REQUEST['openid'])){
			$openid = $_REQUEST['openid'];
			$this->s("openid",$openid);
		}*/
        $this->v("Sweepstakes/Register");
    }


 //注册
    public function RegisterDo() {
        if(!$this->isMobile($_POST['phone'])) {
            $this->error("手机格式不正确");
        }
        if(!$this->isNum($_POST['verification'])) {
            $this->error("验证码格式不正确");
        }
        if(!$this->isPWD($_POST['password'])) {
            $this->error("密码格式不正确");
        }
        $phone = $_POST['phone'];
        $verification = $_POST['verification'];
        $password = $_POST['password'];

        //验证是否登录
        if($this->U['id']){
            $this->error("请退出后再注册");
        }
        //检测是否已被注册
        $result1 = $this->m('user')->where('Phone = '.$phone)->count();
        if($result1) {
            $this->error("该手机号已被注册");
        }
        //检测验证码是否正确
        $result2 = $this->m('verification')->where('Phone = '.$phone)->order('Time desc')->find();
        if($result2['Num'] != $verification) {
            $this->error("验证码不正确");
        }
        if((time()-$result2['Time']) > 300) {
           $this->error("验证码过期");
        }
		if($_REQUEST['openid']){
			 $condition['openid'] = $_REQUEST['openid'];
		}
		$code = md5(rand(0,9999).time());
		$SweepstakesNumber = $this->ScSweepstakesNumber(); //获取6位不重复的数字
		$SweepstakesNumber = $this->SknHq($SweepstakesNumber);//判断数据库中是否存在;
	
        //注册
        $condition['Phone'] = $phone;
        $condition['Password'] = $password;
        $condition['RegDate'] = time();
		
        $result3 = $this->m('user')->add($condition);
        if($result3) {
			$ifstk = $this->m("sweepstakes")->where("Uid =".$result3)->find();//判断是否存在抽奖卷
			if(!$ifstk){
				$dataarr = array(
					'code' => $code,	
					'Uid'  => $result3,	
					'CreateTime' => time(),	
					'Djstatus' => 1,	
					'SweepstakesNumber' => $SweepstakesNumber,
					'MaturityTime' => strtotime(date('Y-m-d'))+24*3600,
					'Ifdel' => 1,
					'Dhstatus' => 1
					);
								
				$res = $this->m("sweepstakes")->add($dataarr);//添加抽奖卷
				if($res){
					$ms = array(
						'content' 	=> '【华采网】恭喜您注册“华采网”成功！并获得品牌充电宝一个!更多机会——特等：价值10000元纪念币一套（1名）；一等：价值5000元华为手机一部(5名)；二等：价值3000元 IPAD MIN4一部(20名)，三等：价值1000元华为手环一个(50名)。具体详情http://www.chnhuacai.com/?m=News&a=NewsContent&id=29',//短信内容

						'mobile' 	=>  $condition['Phone'],//手机号码
					);
					send($ms);
				}
				
				if(!$res){
					$this->error("系统繁忙，请稍后再试!");
				}
			}	
            $user = array(
                'id' => $result3,
                'cid' => 0,
                'pid' => 0,
                'phone' => $phone,
                'CompanyName' => '',
                'UserPhoto' => '',
            );
            session('UserInfo',$user);
            $this->U = session('UserInfo');
			header("Location:http://wap.chnhuacai.com/?m=Index&a=Xzurl");
            //$this->success("您已注册成功,请完善公司信息",T('Index/Index'));
        }else {
            $this->error("系统繁忙，请稍后再试!");
        }
    }


 public function PhoneOnlyAjax(){//手机号码唯一验证
         if(!$this->isMobile($_POST['phone'])) {
             echo 3;
			 exit;
         }
			$phone = $_POST['phone'];
			$onlyhpone = $this->m('user')->where("Phone=".$phone)->count();
			if($onlyhpone){
				echo 1;
				exit;
			}else{
				echo 2;
				exit;
			}
		
			return;

	
	}

	//发送验证码接口
	public function SendVerification(){

		if(!$_POST['phone'] || !$this->isMobile($_POST['phone'])||!$_POST['Token']) {
			echo $status = 4;
			return;
		}
		$Phone = $_POST['phone'];
		$ckecks = $this->CheckVerification($Phone);
		if($ckecks == 1){
			echo $status = 1;die;
		}
		if($ckecks == 2){
			echo $status = 2;die;
		}
		//发送验证码
		$time = time();
		$num =rand(1000, 9999);
		$conditions['Phone'] =$Phone;
		$conditions['Num'] = $num;
		$conditions['Time'] = $time;
		$ms = array(
			'content' 	=> '【华采网】您申请的手机验证码是:'.$num.',请输入后进行验证。提示:请勿泄露给他人',//短信内容
			'mobile' 	=> $Phone,//手机号码
		);
		$sendSt = send($ms);
		$sendSt= explode(',',$sendSt);
		if($sendSt[0]!= 1) {
			echo $status = 4;
			return;
		};
		$results = $this->m('verification')->add($conditions);

		if($results) {
			echo $status = 3;
			return;
		}else{
			echo $status = 4;
			return;
		}
	}
	//验证码发送检查
	public function CheckVerification($Phone){
		//一分钟内不能连续发送
		$last_time = $this->m('verification')->where("Phone = " .$Phone )->order('Time desc')->find();
		if((time() - $last_time['Time']) < 60) {
			return 1;die;
		}
		//一天发送次数不能超过10次
		$start_time = strtotime(date('Y-m-d', time()));
		$end_time = $start_time + 86400;
		$condition["Time"] = array('between',$start_time .' and '. $end_time);
		$condition["Phone"] = $Phone;
		$has_nums = $this->m('verification')->where($condition)->count();
		if($has_nums >9) {
			return 2;die;
		}
//        return 3;
	}

	protected function is_login(){
		$user = session("UserInfo");
		$ComomClass = array('Register');
		if(in_array(\Chinax3::$conf["_action"],$ComomClass)){
			return true;
		}
		if($user){
			$this->s('_me',$user);
			return $this->U = $user;
		}else{
			return false;
		}
	}
	public function GetCompany(){
		if($_SESSION['UserInfo']['cid']){
			$ComSee = $this->m("company")->where("Id=".$_SESSION['UserInfo']['cid'])->field("CompanyName,CompanyLogo")->find();
			$this->s("_ComSee",$ComSee);
		}
		
	}
	public function Logout(){
		unset($_SESSION['UserInfo']);
		header("Location:".$_SERVER['HTTP_REFERER']);
	}	

	public function LoginDo(){
        if(!$_REQUEST['username']||!$_REQUEST['password']) {
            $this->error("手机或密码不能为空");
        }
        if(!$this->isMobile($_POST['username'])) {
            $this->error("手机格式不正确");
        }
        if(!$this->isPWD($_POST['password'])) {
            $this->error("密码格式不正确");
        }
		$w = array("Phone"=>$_POST['username'],'Password' => $_POST['password'],'Status' => 0);
		$info = $this->m('user')->where($w)->find();
		if($info){
			if(isset($info['Cid'])){
				$company = $this->m('company')->where("Id = " . $info['Cid'])->find();
			}else{
				$company['CompanyName']="";
			}
			$user = array(
				'id' => $info['Id'],
				'cid' => $info['Cid'],
				'pid' => $info['Pid'],
				'phone' => $info['Phone'],
				'CompanyName' => $company['CompanyName'],
                'UserPhoto' => $info['UserPhoto'],
			);
			session('UserInfo',$user);
            $this->U = session('UserInfo');
			header("Location:http://wap.chnhuacai.com");
			//$this->success("登录成功",T('Index/Index'));

		}else{
			$this->error("用户名或密码错误");
		}
	}
	
	public function ScSweepstakesNumber(){//随机6位不重复的数字
		static $arr=array();
		  if(count($arr)<6){
				$num = rand(1,9);
				if(in_array($num,$arr)){
					$this->ScSweepstakesNumber();

					
				}else{
					
					array_push($arr,$num);
					$this->ScSweepstakesNumber();

				}
				
			}
		return (int)implode($arr);

	}
	public function SknHq($num){//判断数据库总是否存在此数
		$ifcz = $this->m("sweepstakes")->where("SweepstakesNumber = ".$num)->find();
		if($ifcz){
			$num = $this->ScSweepstakesNumber();
			$this->SknHq($num);
		}
		return $num;
	}

}